<template>
  <div class="product-detail-bg">
    <div class="top-fixed-btns">
      <el-tooltip content="我的收藏" placement="bottom">
        <el-button
          @click="showFavorite = true"
          size="large"
          circle
          class="top-btn"
          type="warning"
          :icon="Star"
        />
      </el-tooltip>
      <el-tooltip content="我的订单" placement="bottom">
        <el-button
          @click="showOrder = true"
          size="large"
          circle
          class="top-btn"
          type="primary"
          :icon="Document"
        />
      </el-tooltip>
      <el-tooltip content="浏览记录" placement="bottom">
        <el-button
          @click="showBrowsing = true"
          size="large"
          circle
          class="top-btn"
          type="success"
          :icon="View"
        />
      </el-tooltip>
      <el-tooltip content="购物车" placement="bottom">
        <el-button
          @click="goCart"
          size="large"
          circle
          class="top-btn cart-btn"
          type="primary"
          :icon="ShoppingCart"
          style="box-shadow: 0 4px 16px rgba(64,158,255,0.25); border: 2px solid #409eff; background: linear-gradient(90deg, #409eff 60%, #66b1ff 100%); color: #fff;"
        />
      </el-tooltip>
    </div>
    <div class="product-detail-page" v-if="product">
      <el-row :gutter="40" align="top">
        <el-col :xs="24" :md="12">
          <el-carousel height="480px" v-if="product.detail && product.detail.detail_images.length">
            <el-carousel-item v-for="(img, idx) in product.detail.detail_images" :key="idx">
              <img :src="img" class="detail-img" />
            </el-carousel-item>
          </el-carousel>
          <img v-else :src="product.cover_image" class="detail-img" />
        </el-col>
        <el-col :xs="24" :md="12">
          <div class="main-info">
            <h1 class="product-title">{{ product.name }}</h1>
            <div class="price-row">
              <span class="price">￥{{ product.price }}</span>
              <span class="original">￥{{ product.original_price }}</span>
              <el-tag v-if="product.tag" type="success" class="ml-10">{{ product.tag }}</el-tag>
              <el-tag v-if="product.is_new" type="warning" class="ml-10">NEW</el-tag>
            </div>
            <div class="short-desc">{{ product.short_desc }}</div>
            <div class="stock">库存：{{ product.detail?.stock ?? 0 }}</div>
            <el-button :type="isFavorited ? 'danger' : 'primary'" @click="handleFavorite" class="ml-10">
              {{ isFavorited ? '取消收藏' : '收藏' }}
            </el-button>
            <el-button type="success" @click="handleOrder" class="ml-10">购买</el-button>
            <el-divider />
            <div class="desc-title">商品详情</div>
            <div class="desc-content">{{ product.detail?.description }}</div>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-empty v-else description="未找到商品" />
    <el-dialog v-model="orderDialogVisible" title="下单" width="350px" :close-on-click-modal="false">
      <div style="text-align:center;">
        <div style="margin-bottom:16px;">{{ product.name }}</div>
        <div style="margin-bottom:16px;">单价：￥{{ product.price }}</div>
        <div style="margin-bottom:16px;">
          数量：
          <el-button size="small" @click="orderQuantity = Math.max(1, orderQuantity-1)">-</el-button>
          <span style="margin:0 12px;">{{ orderQuantity }}</span>
          <el-button size="small" @click="orderQuantity = orderQuantity+1">+</el-button>
        </div>
        <div style="margin-bottom:16px;">总价：￥{{ (product.price * orderQuantity).toFixed(2) }}</div>
        <el-button type="success" @click="onOrderDialogConfirm">确认下单</el-button>
      </div>
    </el-dialog>

    <!-- 收藏列表弹窗 -->
    <el-dialog v-model="showFavorite" title="我的收藏" width="700px" @close="favoriteList = []">
      <el-table :data="favoriteList" style="width:100%" v-loading="loadingFavorite" empty-text="暂无收藏">
        <el-table-column label="图片" width="80">
          <template #default="scope">
            <img :src="fullImg(scope.row.product.cover_image)" style="width:60px;height:60px;object-fit:cover;border-radius:8px;cursor:pointer;" @click="goDetail(scope.row.product.id)" />
          </template>
        </el-table-column>
        <el-table-column prop="product.name" label="商品" min-width="120">
          <template #default="scope">
            <span style="color:#409eff;cursor:pointer;" @click="goDetail(scope.row.product.id)">{{ scope.row.product.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="product.price" label="价格" width="80" />
        <el-table-column prop="timestamp" label="收藏时间" min-width="160">
          <template #default="scope">
            {{ formatTime(scope.row.timestamp) }}
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:center;margin-top:12px;">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="favoriteTotal"
          :page-size="favoritePageSize"
          :current-page="favoritePage"
          @current-change="handleFavoritePageChange"
          :pager-count="7"
          hide-on-single-page
        />
      </div>
    </el-dialog>

    <!-- 订单列表弹窗 -->
    <el-dialog v-model="showOrder" title="我的订单" width="800px" @close="orderList = []">
      <el-table :data="orderList" style="width:100%" v-loading="loadingOrder" empty-text="暂无订单">
        <el-table-column label="图片" width="80">
          <template #default="scope">
            <img :src="fullImg(scope.row.product.cover_image)" style="width:60px;height:60px;object-fit:cover;border-radius:8px;cursor:pointer;" @click="goDetail(scope.row.product.id)" />
          </template>
        </el-table-column>
        <el-table-column prop="product.name" label="商品" min-width="120">
          <template #default="scope">
            <span style="color:#409eff;cursor:pointer;" @click="goDetail(scope.row.product.id)">{{ scope.row.product.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="product.price" label="单价" width="80" />
        <el-table-column prop="quantity" label="数量" width="60" />
        <el-table-column label="总价" width="100">
          <template #default="scope">
            ￥{{ (scope.row.product.price * scope.row.quantity).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="timestamp" label="下单时间" min-width="160">
          <template #default="scope">
            {{ formatTime(scope.row.timestamp) }}
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:center;margin-top:12px;">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="orderTotal"
          :page-size="orderPageSize"
          :current-page="orderPage"
          @current-change="handleOrderPageChange"
          :pager-count="7"
          hide-on-single-page
        />
      </div>
    </el-dialog>

    <!-- 浏览记录弹窗 -->
    <el-dialog v-model="showBrowsing" title="浏览记录" width="800px" @close="browsingList = []">
      <el-table :data="browsingList" style="width:100%" v-loading="loadingBrowsing" empty-text="暂无浏览记录">
        <el-table-column label="图片" width="80">
          <template #default="scope">
            <img :src="fullImg(scope.row.product.cover_image)" style="width:60px;height:60px;object-fit:cover;border-radius:8px;cursor:pointer;" @click="goDetail(scope.row.product.id)" />
          </template>
        </el-table-column>
        <el-table-column prop="product.name" label="商品" min-width="120">
          <template #default="scope">
            <span style="color:#409eff;cursor:pointer;" @click="goDetail(scope.row.product.id)">{{ scope.row.product.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="浏览次数" width="80" />
        <el-table-column prop="timestamp" label="最后浏览时间" min-width="160">
          <template #default="scope">
            {{ formatTime(scope.row.timestamp) }}
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:center;margin-top:12px;">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="browsingTotal"
          :page-size="browsingPageSize"
          :current-page="browsingPage"
          @current-change="handleBrowsingPageChange"
          :pager-count="7"
          hide-on-single-page
        />
      </div>
    </el-dialog>

    <!-- 购物车弹窗 -->
    <el-dialog v-model="showCartDialog" title="请选择操作" width="350px">
      <div style="text-align:center;">
        <el-button type="primary" @click="addToCart">加入购物车</el-button>
        <el-button type="success" @click="onDirectPay">直接支付</el-button>
      </div>
    </el-dialog>

    <!-- 幂等性弹窗 -->
    <el-dialog v-model="showIdempotentDialog" title="重复下单提醒" width="350px">
      <div style="text-align:center;">
        <div style="margin-bottom:16px;">您刚刚已下单该商品，是否继续？</div>
        <el-button type="primary" @click="onContinueOrder">继续</el-button>
        <el-button @click="showIdempotentDialog = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/request'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import { Star, Document, View, ShoppingCart } from '@element-plus/icons-vue'


const route = useRoute()
const router = useRouter()
const product = ref(null)
const userStore = useUserStore()
const isFavorited = ref(false)
const orderDialogVisible = ref(false)
const orderQuantity = ref(1)
const showFavorite = ref(false)
const showOrder = ref(false)
const showBrowsing = ref(false)
const favoriteList = ref([])
const orderList = ref([])
const browsingList = ref([])
const loadingFavorite = ref(false)
const loadingOrder = ref(false)
const loadingBrowsing = ref(false)
const showCartDialog = ref(false)
const showIdempotentDialog = ref(false)
const lastOrderInfo = ref({ id: null, time: null })
const cartList = ref([])

onMounted(async () => {
  const id = route.params.id
  try {
    const res = await request.get(`/shop/products/${id}/`)
    product.value = res
  } catch (e) {
    product.value = null
    return
  }
  // 自动添加浏览记录
  if (userStore.userid && product.value?.id) {
    try {
      await request.post('/shop/browse/', {
        userid: userStore.userid,
        goodsid: product.value.id
      })
    } catch (e) {
      // 忽略浏览记录失败
    }
  }
  // 收藏查询单独 try，不影响主页显示
  if (userStore.userid && product.value?.id) {
    try {
      const favRes = await request.get('/shop/favorite/list/', {
        params: { userid: userStore.userid }
      })
      const favorites = favRes.data && favRes.data.favorites ? favRes.data.favorites : (favRes.favorites || []);
      isFavorited.value = favorites.some(f => f.product.id === product.value.id)
    } catch (e) {
      isFavorited.value = false
    }
  }
})

const handleFavorite = async () => {
  if (!userStore.userid || !product.value?.id) {
    ElMessage.warning('请先登录')
    return
  }
  const res = await request.post('/shop/favorite/', {
    userid: userStore.userid,
    goodsid: product.value.id
  })
  isFavorited.value = res.is_favorited
  ElMessage.success(isFavorited.value ? '收藏成功' : '已取消收藏')
}

const handleOrder = () => {
  orderDialogVisible.value = true
}

const fetchFavorite = async () => {
  loadingFavorite.value = true
  const res = await request.get('/shop/favorite/list/', {
    params: { userid: userStore.userid }
  })
  favoriteList.value = res.favorites || []
  loadingFavorite.value = false
}
const fetchOrder = async () => {
  loadingOrder.value = true
  const res = await request.get('/shop/order/list/', {
    params: { userid: userStore.userid }
  })
  orderList.value = res.orders || []
  loadingOrder.value = false
}
const fetchBrowsing = async () => {
  loadingBrowsing.value = true
  const res = await request.get('/shop/browse/list/', {
    params: { userid: userStore.userid }
  })
  browsingList.value = res.browsings || []
  loadingBrowsing.value = false
}

// 监听弹窗打开时加载数据
watch(showFavorite, v => v && fetchFavorite())
watch(showOrder, v => v && fetchOrder())
watch(showBrowsing, v => v && fetchBrowsing())

function formatTime(time) {
  if (!time) return ''
  const d = new Date(time)
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`
}

// 确保 fullImg 方法存在
const fullImg = url => url && url.startsWith('http') ? url : `http://127.0.0.1:8000/media${url}`

// 加入购物车
async function addToCart() {
  // 先获取购物车列表
  await fetchCartList()
  const exists = cartList.value.some(item => item.product.id === product.value.id)
  if (exists) {
    ElMessage.info('该商品已在购物车中')
    showCartDialog.value = false
    return
  }
  const res = await request.post('/shop/cart/', {
    userid: userStore.userid,
    goodsid: product.value.id,
    quantity: orderQuantity.value
  })
  if (res.code === 200) {
    ElMessage.success('已加入购物车')
    showCartDialog.value = false
  } else {
    ElMessage.error(res.msg || '加入购物车失败')
  }
}

async function fetchCartList() {
  const res = await request.get('/shop/cart/', {
    params: { userid: userStore.userid }
  })
  cartList.value = res.carts || []
}

async function removeCartItem(cartid) {
  const res = await request.delete('/shop/cart/', {
    data: { cartid }
  })
  if (res.code === 200) {
    ElMessage.success('已移除')
    fetchCartList()
  }
}

async function updateCartQuantity(cartid, quantity) {
  const res = await request.patch('/shop/cart/', {
    cartid,
    quantity
  })
  if (res.code === 200) {
    ElMessage.success('数量已更新')
    fetchCartList()
  }
}

function onOrderDialogConfirm() {
  orderDialogVisible.value = false
  const now = Date.now()
  const FIVE_MIN = 5 * 60 * 1000
  if (
    lastOrderInfo.value.id === product.value.id &&
    lastOrderInfo.value.time &&
    now - lastOrderInfo.value.time < FIVE_MIN
  ) {
    showIdempotentDialog.value = true
  } else {
    showCartDialog.value = true
  }
}

function onContinueOrder() {
  showIdempotentDialog.value = false
  showCartDialog.value = true
}

async function onDirectPay() {
  const res = await request.post('/shop/alipay/order/', {
    userid: userStore.userid,
    goodsid: product.value.id,
    quantity: orderQuantity.value
  })
  if (res.code === 0 && res.pay_url && res.pay_url.startsWith('https://openapi-sandbox.dl.alipaydev.com/gateway.do')) {
    window.location.href = res.pay_url
  } else {
    ElMessage.error(res.msg || '支付失败')
  }
}

function goCart() {
  router.push('/cart')
}

async function payForItem(item) {
  const res = await request.post('/shop/alipay/order/', {
    userid: userStore.userid,
    goodsid: item.product.id,
    quantity: item.quantity
  })
  if (res.code === 0) {
    window.location.href = res.pay_url
  } else {
    ElMessage.error(res.msg || '支付失败')
  }
}

function goDetail(id) {
  router.push(`/shop/${id}`)
}
</script>

<style scoped>
.product-detail-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #f0f1f2 100%);
  padding: 0;
  margin: 0;
}
.product-detail-page {
  margin: 0 auto;
  padding: 48px 5vw 48px 5vw;
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 32px 0 rgba(0,0,0,0.07);
  min-height: 600px;
}
.detail-img {
  width: 100%;
  height: 480px;
  object-fit: cover;
  border-radius: 14px;
  background: #f5f7fa;
  box-shadow: 0 2px 12px #e0e0e0;
}
.main-info {
  padding: 0 0 0 0;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  height: 100%;
}
.product-title {
  font-size: 2.2rem;
  font-weight: 700;
  margin-bottom: 18px;
  color: #222;
}
.price-row {
  margin: 18px 0 10px 0;
  font-size: 2rem;
  color: #f56c6c;
  font-weight: bold;
  display: flex;
  align-items: center;
}
.price {
  margin-right: 18px;
  font-size: 2.2rem;
}
.original {
  color: #bbb;
  text-decoration: line-through;
  font-size: 1.2rem;
  margin-right: 12px;
}
.ml-10 {
  margin-left: 10px;
}
.short-desc {
  color: #888;
  font-size: 1.1rem;
  margin-bottom: 18px;
}
.stock {
  color: #409eff;
  font-size: 1.1rem;
  margin-bottom: 18px;
}
.desc-title {
  font-weight: bold;
  font-size: 1.3rem;
  margin: 24px 0 10px 0;
}
.desc-content {
  color: #333;
  font-size: 1.1rem;
  line-height: 1.8;
  background: #f8f8f8;
  padding: 22px;
  border-radius: 10px;
  min-height: 120px;
}
@media (max-width: 900px) {
  .product-detail-page {
    padding: 24px 2vw;
  }
  .detail-img {
    height: 260px;
  }
  .main-info {
    padding: 0;
  }
  .product-title {
    font-size: 1.3rem;
  }
  .price-row {
    font-size: 1.2rem;
  }
}
.top-fixed-btns {
  position: fixed;
  top: 24px;
  right: 32px;
  z-index: 100;
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.top-btn {
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  transition: box-shadow 0.2s, background 0.2s;
}
.top-btn:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.16);
  filter: brightness(1.08);
}
@media (max-width: 600px) {
  .top-fixed-btns {
    top: 12px;
    right: 8px;
    gap: 10px;
  }
  .top-btn {
    width: 38px !important;
    height: 38px !important;
    font-size: 18px !important;
  }
}
.cart-btn {
  animation: cart-pop 0.6s;
  border-radius: 50% !important;
  font-size: 22px !important;
  background: linear-gradient(90deg, #409eff 60%, #66b1ff 100%) !important;
  color: #fff !important;
  border: 2px solid #409eff !important;
  box-shadow: 0 4px 16px rgba(64,158,255,0.25) !important;
  transition: box-shadow 0.2s, background 0.2s;
}
.cart-btn:hover {
  box-shadow: 0 8px 32px rgba(64,158,255,0.35) !important;
  filter: brightness(1.08);
}
@keyframes cart-pop {
  0% { transform: scale(0.7); }
  70% { transform: scale(1.15); }
  100% { transform: scale(1); }
}
</style>